package com.shujia.scala

import scala.io.Source

object Demo22SumScore {
  def main(args: Array[String]): Unit = {
    /**
     * 2、统计学生的总分
     */

    //1、读取分数表
    val scoresList: List[String] = Source.fromFile("data/score.txt").getLines().toList


    //2、过滤脏数据
    val filterList: List[String] = scoresList.filter((line: String) => {
      val length: Int = line.split(",").length
      length == 3
    })

    //3、取出学号和分数
    val idAndScore: List[(String, Int)] = filterList.map((line => {
      val split: Array[String] = line.split(",")
      //学号
      val id: String = split.head
      //分数
      val score: Int = split.last.toInt
      (id, score)
    }))

    //4、按照学号分组
    val groupByList: Map[String, List[(String, Int)]] = idAndScore.groupBy(kv => kv._1)

    //5、统计学生的总分
    val sumScoMap: Map[String, Int] = groupByList.map((kv: (String, List[(String, Int)])) => {
      val id: String = kv._1
      val scores: List[(String, Int)] = kv._2
      //取出每个学生所有的分数
      val scos: List[Int] = scores.map(sco => sco._2)
      //计算总分
      val sumSco: Int = scos.sum

      (id, sumSco)
    })

    sumScoMap.foreach(println)
  }

}
